<?php

namespace plugin\admin\app\model;

use app\services\RequestService;
use plugin\admin\app\model\Base;
use support\Cache;


class YbUser extends Base
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_yb_user';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    protected $guarded = [];

    public static function getCustomerId($customer_number,$appid='')
    {
        $customer_id = Cache::get('customer_id-'.$customer_number);
        if (empty($customer_id)){
           $customer_id = self::where('customer_number',$customer_number)->value('customer_uid');
           if (!empty($customer_id)){
               Cache::set('customer_id-'.$customer_number,$customer_id);
               return $customer_id;
           }
        }elseif (!empty($customer_id)){
            return $customer_id;
        }
        $customerInfo = RequestService::customerInfoByNumber($appid,$customer_number);
        if (!empty($customerInfo['status']) && $customerInfo['status'] == 'success'){
            YbUser::create([
                'customer_number'=>$customer_number,
                'customer_uid' => $customerInfo['data']['customerUid'],
                'phone' => $customerInfo['data']['phone'],
                'name' => $customerInfo['data']['name']
            ]);
            $customer_id = $customerInfo['data']['customerUid'];
            Cache::set('customer_id-'.$customer_number,$customer_id);
        }
        return $customer_id??'';
    }

    public static function getCustomerNumber($customer_id,$appid='')
    {
        $customer_number = Cache::get('customer_number-'.$customer_id);
        if (empty($customer_id)){
            $customer_number = self::where('customer_uid',$customer_id)->value('customer_number');
            if (!empty($customer_number)){
                Cache::set('customer_number-'.$customer_id,$customer_number);
                return $customer_number;
            }
        }elseif (!empty($customer_number)){
            return $customer_number;
        }
        $customerInfo = RequestService::customerInfoById($appid,$customer_id);
        if (!empty($customerInfo['status']) && $customerInfo['status'] == 'success'){
            YbUser::create([
                'customer_number'=>$customerInfo['data']['number'],
                'customer_uid' => $customerInfo['data']['customerUid'],
                'phone' => $customerInfo['data']['phone'],
                'name' => $customerInfo['data']['name']
            ]);
            $customer_number = $customerInfo['data']['number'];
            Cache::set('customer_number-'.$customer_id,$customer_number);
        }
        return $customer_number??'';
    }
    
    
    
    
}
